package com.isesol.seckill.config;

import com.alibaba.dubbo.config.*;
import com.alibaba.dubbo.config.spring.*;
import com.isesol.seckill.service.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.context.annotation.*;

import javax.annotation.*;

@Configuration
@EnableAutoConfiguration
public class DubboConfig {

    private int retries = 0;
    private int timeout = 10000;

    @Value("${dubbo.registry.url}")
    private String dubboRegistryUrl;

    @Bean(name = "application")
    public ApplicationConfig application() {

        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName("seckill");

        return applicationConfig;
    }

    @Bean
    public RegistryConfig registry() {

        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress(dubboRegistryUrl);
        registryConfig.setProtocol("dubbo");

        return registryConfig;
    }

    @Bean
    public ProtocolConfig protocol() {

        ProtocolConfig protocolConfig = new ProtocolConfig();
        protocolConfig.setPort(-1);

        return protocolConfig;
    }

    @Bean
    public ProviderConfig provider() {

        ProviderConfig providerConfig = new ProviderConfig();

        return providerConfig;
    }

    /**
     * countService
     * @param countService
     * @return
     */
    @Bean
    @Resource
    public ServiceBean exportCountService(CountService countService) {

        ServiceBean serviceBean = buildServiceBean(timeout);
        serviceBean.setInterface(CountService.class);
        serviceBean.setRef(countService);
        serviceBean.setRetries(retries);

        return serviceBean;
    }
    /**
     * countService
     * @param secKillService
     * @return
     */
    @Bean
    @Resource
    public ServiceBean exportSecKillService(SecKillService secKillService) {

        ServiceBean serviceBean = buildServiceBean(timeout);
        serviceBean.setInterface(SecKillService.class);
        serviceBean.setRef(secKillService);
        serviceBean.setRetries(retries);

        return serviceBean;
    }

    public ServiceBean buildServiceBean(Integer timeout){

        ServiceBean serviceBean = new ServiceBean();
        serviceBean.setProxy("javassist");
         serviceBean.setTimeout(timeout);

        return serviceBean;
    }

}
